package com.ljw.punishment.enginelistener;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component(value = "logRuleListener")
public class LogRuleListener implements RuleListener {


    @Override
    public boolean beforeEvaluate(Rule rule, Facts facts) {
        String beforeEvaluate = PrintRuleHelper.printRule("beforeEvaluate", rule);
        log.info("====logRuleListener::beforeEvaluate ====加载规则：{},  加载事实:{}", beforeEvaluate,
                JSONObject.toJSONString(facts));
        return true;
    }

    @Override
    public void afterEvaluate(Rule rule, Facts facts, boolean evaluationResult) {
        RuleEvaluateLogDAO ruleEvaluateLogDAO = new RuleEvaluateLogDAO();
        ruleEvaluateLogDAO.setRuleName(rule.getName());
        String afterEvaluate = PrintRuleHelper.printRule("afterEvaluate", rule);
        ruleEvaluateLogDAO.setRuleJson(afterEvaluate);
        log.info("====logRuleListener::afterEvaluate ==== 加载事实:{} ,计算结果:{}", JSONObject.toJSONString(facts), JSONObject.toJSONString(evaluationResult));
        ruleEvaluateLogDAO.setFacts(JSONObject.toJSONString(facts));
        ruleEvaluateLogDAO.setResult(evaluationResult ? 1 : 0);
    }

    @Override
    public void onEvaluationError(Rule rule, Facts facts, Exception exception) {
        String afterEvaluate = PrintRuleHelper.printRule("onEvaluationError", rule);
        log.error("====logRuleListener::onEvaluationError ==== 规则计算异常:rule : {} , fact ：{} ", afterEvaluate, JSONObject.toJSONString(facts), exception);
        new Exception("规则编译异常" + exception.getMessage());
    }

    @Override
    public void beforeExecute(Rule rule, Facts facts) {
        log.info("====logRuleListener::beforeExecute ==== 规则执行前: fact:{}", JSONObject.toJSONString(facts));
    }

    @Override
    public void onSuccess(Rule rule, Facts facts) {
        log.info("====logRuleListener::onSuccess ==== 规则执行成功: fact:{}", JSONObject.toJSONString(facts));
    }

    @Override
    public void onFailure(Rule rule, Facts facts, Exception exception) {
        String afterEvaluate = PrintRuleHelper.printRule("onFailure", rule);
        log.error("====logRuleListener::onFailure ==== 规则执行异常:rule : {} , fact ：{} ", afterEvaluate, JSONObject.toJSONString(facts), exception);
    }
}
